import React, { useEffect, useState, useRef } from "react";
const useMsg = (url: string) => {
  let socket = useRef<WebSocket | null>(null);
  const [msg, setMsg] = useState<any>();
  useEffect(() => {
    socket.current = new WebSocket(url);
    socket.current.onmessage = (e) => {
      setMsg(e.data);
    };
    socket.current.onclose = () => {
      socket.current = new WebSocket(url);
    };
  }, [url]);
  const send = (data: any) => {
    socket.current?.send(JSON.stringify(data));
  };
  return {
    msg,
    send,
  };
};
export default useMsg;
